import { reactive, ref } from 'vue'
import { kefuCallPhone } from '@/Pinia/index'
import { takeAwayNext, takeAwayDeliveryin, runErrandDistributionDeltails, runErrandWaitPickItemDelails } from '@/utlis/interface/orderDlatils'
import { getLocation } from '@/utlis/uni_api'
interface loactionData {
  lng: number,
  lat: number
}
interface data {
  id: number | null,
  Type: number | null,
  orderType: number | null

}
export default (Props: any, Proxy: any) => {
  const { phoneNumber } = kefuCallPhone()
  //当前坐标定位点
  const nowCoordinate = reactive<any>({
    starLongitude: null,
    starLatitude: null,
  })
  //客服电话
  const makePhone = () => {
    const { phonelist } = kefuCallPhone()
    phoneNumber('itemMap')
    const kefuNumber = phonelist.list
    uni.makePhoneCall({
      phoneNumber: kefuNumber
    })
  }
  const polyline = reactive([
    {
      points: Props.polylines,
      dottedLine: true,
      arrowLine: true,
      color: "#33b166",
      width: 8,
    },
  ]);
  const MarkLoaction = reactive<any>({
    longitude: null,
    latitude: null,
  })
  const covers = reactive<any>([
    {
      latitude: null,
      longitude: null,
      width: 70,
      height: 70,
      title: "",
      iconPath: "../../static/images/pulice/closed.png",
    }
  ]);
  const showData = reactive<any>({
    mapShow: true,
    loadingShow: false,
    drawLineShow: false
  })
  let mapChangeTime: any = null
  //地图视野发生变化时触发
  const mapChangeOver = () => {
    // 清除骑手位置更新 优化性能
    clearTimeout(timer.value)
    showData.mapShow = false
    if (mapChangeTime) {
      // 防抖事件
      clearTimeout(mapChangeTime)
    }
    // 延迟
    mapChangeTime = setTimeout(() => {
      showData.mapShow = true
      onLoadLoaction()
    }, 1500)
  }

  // 初始化点坐标
  const loactionData = reactive<loactionData>({
    lat: 0,
    lng: 0
  })

  /*@parmars ID */
  const baseData = reactive<data>({
    id: null,
    Type: null,
    orderType: null

  })

  const mapUpdateOver = () => {
    console.log('地图绘制完成')
    clearTimeout(timer.value)
    // 绘制完成 调用骑手频率更新接口
    onLoadLoaction()
  }
  let RiderNum = 0 //骑手调用次数
  let timer = ref<any>('')
  /**
   * @骑手频率更新
   * @注解 骑手每3秒更新一次频率 每更新10次更新一次线路接口
   */
  const onLoadLoaction = () => {
    if (showData.mapShow && showData.drawLineShow) {
      // 骑手位置每调用10次 就更新一次线路
      if (RiderNum == 10) {
        reDrawLine2(() => {
          RiderNum = 0
          UpdateRiderAdd()
        })
      } else {
        timer.value = setTimeout(() => {
          UpdateRiderAdd()
        }, 3000);
      }
    }
  }
  // 更新骑手位置
  const UpdateRiderAdd = () => {
    getLocation().then((response: any) => {
      if (response.latitude != null) {
        let locations = response.longitude + "," + response.latitude;
        // 转换坐标
        Proxy.$API(Proxy).CoordinateTransformation(locations,true).then((res: { longitude: string; latitude: string }) => {
          // 骑手频率递增
          RiderNum++
          console.log(RiderNum, '当前骑手频率')
          //重新设置当前位置
          MarkLoaction.latitude = res.latitude
          MarkLoaction.longitude = res.longitude
          covers[1].latitude = MarkLoaction.latitude
          covers[1].longitude = MarkLoaction.longitude
          nowCoordinate.starLatitude = MarkLoaction.latitude
          nowCoordinate.starLongitude = MarkLoaction.longitude
          uni.setStorageSync('riderLongitude', res.longitude)
          uni.setStorageSync('riderLatitude', res.latitude)
          onLoadLoaction()
        })
      }
    });
  }
  /**
    * @新版详情接口画线
    * @param CallBack  回调函数
    */
  const reDrawLine2 = (CallBack: Function) => {
    // 递归调用
    let data = {
      latitude: MarkLoaction.latitude,
      longitude: MarkLoaction.longitude,
      orderId: baseData.id
    }
    // 详情接口
    runErrandDistributionDeltails(data, Proxy).then((res: any) => {
      if (res.code == 0) {
        lineArrayReset2(res, CallBack)
      }
    }).catch((err: any) => {
      // 失败就自己掉自己 直到获取成功为止
      //reDrawLine2(CallBack)
      Proxy.$API(Proxy).Toast(err.msg, 'error')
    })
  }
  /**
   * @赋值地图划线数组
   * @param res   接口值
   * @param CallBack 回调函数
   */
  const lineArrayReset2 = (res: any, CallBack: Function) => {
    if (res.code == 0) {
      polyline[0].points = []
      let list: any = []
      res.data.locationVO.locationResultVOs?.forEach((item: any, index: number) => {
        list.push(item)
        polyline[0].points = list
      })
      CallBack()
    }
  }


  // uni.startLocationUpdate({
  //   success: ((res: any) => {
  //     // 成功开启定位后进行实时位置更新
  //     riderLoactionChange()
  //   }),
  //   fail: ((err: any) => {
  //     console.log(err);
  //     //定位失败检测是否开启定位权限   或者GPRS 定位
  //   })
  // })

  // const riderLoactionChange = () => {
  //   uni.onLocationChange((res: any) => {
  //     //重新设置当前位置
  //     loactionData.lng = res.longitude
  //     loactionData.lat = res.latitude
  //     MarkLoaction.latitude = res.latitude
  //     MarkLoaction.longitude = res.longitude
  //     nowCoordinate.starLatitude = res.latitude
  //     nowCoordinate.starLongitude = res.longitude
  //     covers[1].latitude = res.latitude
  //     covers[1].longitude = res.longitude
  //   })
  // }

  /**
   *
  Type?: number // 0:新任务 1:待取货 2:配送中
  orderlist: any
  orderType: number // {0,1}  0 外卖  1跑腿
   *
   */

  //  重新画线
  // let drawlineTimer: any;
  // const reDrawLine = (options: any) => {
  //   baseData.id = options.id
  //   baseData.Type = options.Type
  //   baseData.orderType = options.orderType
  //   let data = {
  //     latitude: MarkLoaction.latitude,
  //     longitude: MarkLoaction.longitude,
  //     orderId: baseData.id
  //   }
  //   clearTimeout(drawlineTimer)
  //   if (showData.drawLineShow) {
  //     drawlineTimer = setTimeout(() => {
  //       reDrawLine(baseData)
  //       if (MarkLoaction.longitude !== null) {
  //         runErrandDistributionDeltails(data, Proxy).then((res: any) => {
  //           if (res.code == 0) {
  //             polyline[0].points = []
  //             let list: any = []
  //             res.data.locationVO.locationResultVOs?.forEach((item: any, index: number) => {
  //               list.push(item)
  //               polyline[0].points = list
  //             })
  //           }
  //         }).catch((err: any) => {
  //           Proxy.$API(Proxy).Toast(err.msg, 'error')
  //         })
  //       }
  //     }, 30000)
  //   }
  // }


  // //赋值地图划线数组
  // const lineArrayReset = (res: any) => {
  //   if (res.code == 0) {
  //     polyline[0].points = []
  //     let list: any = []
  //     res.data.locationVO.locationResultVOs?.forEach((item: any, index: number) => {
  //       list.push(item)
  //       polyline[0].points = list
  //     })
  //   }
  // }
  return {
    nowCoordinate,
    makePhone,
    onLoadLoaction,
    covers,
    phoneNumber,
    polyline,
    mapChangeOver,
    mapUpdateOver,
    // moveLoaction,
    // riderLoactionChange,
    // reDrawLine,
    // drawlineTimer,
    MarkLoaction,
    loactionData,

    showData,
    timer,
    baseData
  }
}
